//
//  WLRouterDeviceManagerController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/18.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRouterDeviceManagerController.h"
#import "WLDeviceManagerCell.h"
#import "WLRouterDeviceModel.h"
#import "WLAlertView.h"
#import "UIScrollView+EmptyDataSet.h"

@interface WLRouterDeviceManagerController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>//,RouterSocketDelegate>

@property (nonatomic, strong) UITableView   *tbDevices;
@property (nonatomic, strong) NSMutableArray    *arrDevices;
@property (nonatomic, strong) NSTimer *timerRefresh;

@end

@implementation WLRouterDeviceManagerController

- (void)dealloc
{
//    [[WLSocketManager sharedSocketManager] removeDelegate:self];
    [[WLSocketManager sharedSocketManager] removeDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timerRefresh invalidate];
    _timerRefresh = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"联网设备管理";
    
    _arrDevices = [[NSMutableArray alloc] init];
    _tbDevices = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbDevices.backgroundColor = wlUIColorRGB(0xFAFAFA);
    _tbDevices.delegate = self;
    _tbDevices.dataSource = self;
    _tbDevices.rowHeight = WLScaleX(80);
    _tbDevices.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)) {
        _tbDevices.estimatedSectionHeaderHeight = 0;
    }
    [self.view addSubview:_tbDevices];
    WLWkSelf
    [_tbDevices mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    self.tbDevices.emptyDataSetSource = self;
    self.tbDevices.emptyDataSetDelegate = self;
    
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
    [[WLSocketManager sharedSocketManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
//    [self receiveRouterConnectDevice];
    [self.timerRefresh fire];
}

- (NSTimer *)timerRefresh
{
    if (!_timerRefresh) {
        _timerRefresh = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(receiveRouterConnectDevice) userInfo:nil repeats:YES];
    }
    return _timerRefresh;
}

- (void)receiveRouterBlackSet:(NSString *)strDevice
{
    NSDictionary *dict = @{@"type":@"DEVICE_BLACKADD_SET",@"content":strDevice};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)receiveRouterConnectDevice
{
    NSDictionary *dict = @{@"type":@"DEVICE_NET_DEVICE_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
    if ([msgModel.type isEqualToString:@"DEVICE_NET_DEVICE_REP"])
    {
        if (msgModel.content != nil) {
//            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
//            NSError *err;
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                                options:NSJSONReadingMutableContainers
//                                                                  error:&err];
            self.arrDevices = [WLRouterDeviceModel mj_objectArrayWithKeyValuesArray:msgModel.content];
            if (self.tbDevices.editing==NO) {
                [self.tbDevices reloadData];
            }
        }
    }
    else if ([msgModel.type isEqualToString:@"COMMON_SUCCESS"])
    {
        if ([msgModel.replyType isEqualToString:@"DEVICE_BLACKADD_SET"]) {
            [self showHUDMessage:@"设置成功"];
        }
//        [self receiveRouterConnectDevice];
    }
}


#pragma mark - UITableView
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
//    WLRouterDeviceModel *model = self.arrDevices[indexPath.row];
//    if ([model[@"current"] integerValue] == 1)
//    {
//        return NO;
//    }
    return YES;
}
/**.点击删除的实现。特别提醒：必须要先删除了数据，才能再执行删除的动画或者其他操作，不然会引起崩溃。*/
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (NSArray*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    WLRouterDeviceModel *device = self.arrDevices[indexPath.row];
    // delete action
    if (device.access)
    {
        WLWkSelf
        UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"加入黑名单" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            [weakSelf doBlackAction:device];
            [tableView setEditing:NO animated:YES];
        }];
        return @[deleteAction];
    }
    else
    {
        UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"已在黑名单" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            
            [tableView setEditing:NO animated:YES];
        }];
        return @[deleteAction];
    }
//    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:NSLocalizedString(@"DeleteLabel", @"") handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
//        [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
//    }];
    
//    // read action
//    // 根据cell当前的状态改变选项文字
//    NSInteger index = indexPath.section;
//    BOOL isRead = [[NotificationManager instance] read:index];
//    NSString *readTitle = isRead ? @"Unread" : @"Read";
//
//    // 创建action
//    UITableViewRowAction *readAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:readTitle handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
//    {
//        [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
//    }];
    
//    return @[deleteAction];
}
/*
-  (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"+黑名单";
}
*/
- (void)openBlackStatus
{
    NSDictionary *dictParamer = @{@"bOpen":@(YES)};
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParamer options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *strContent = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *dict = @{@"type":@"DEVICE_BLACK_STATUS_SET",@"content":strContent};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)addDevieceToBlack:(WLRouterDeviceModel *)deviceModel
{
    [self openBlackStatus];
    self.isOpenBlacks = YES;
    NSDictionary *dictLast = @{@"name":deviceModel.name,@"macAddress":deviceModel.macAddress};
    NSString *strContent = dictLast.mj_JSONString;
    NSDictionary *dict = @{@"type":@"DEVICE_BLACKADD_SET",@"content":strContent};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)doBlackAction:(WLRouterDeviceModel *)device
{
    if (self.isOpenBlacks) {
        NSDictionary *dictLast = @{@"name":device.name,@"macAddress":device.macAddress};
        NSString *dictStr = dictLast.mj_JSONString;
        [self receiveRouterBlackSet:dictStr];
    }
    else
    {
        [self showHUDMessage:@"请先打开防火墙"];
//        WLWkSelf
//        WLAlertView *alertView = [[WLAlertView alloc] initWithTitle:@"提示" message:@"请先打开防火墙" cancelBtnTitle:nil goBtnTitle:@"打开"];
//        alertView.okAction = ^{
//            [weakSelf addDevieceToBlack:device];
//        };
//        [alertView show];
    }
}
/*
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    WLRouterDeviceModel *device = self.arrDevices[indexPath.row];
    [self doBlackAction:device];
    
//    WLRouterDeviceModel *device = self.arrDevices[indexPath.row];
////    NSMutableDictionary *dictBlack = device.mj_keyValues;
//    NSDictionary *dictLast = @{@"name":device.name,@"macAddress":device.macAddress};
//    NSString *dictStr = dictLast.mj_JSONString;
//    [self receiveRouterBlackSet:dictStr];
    
//    NSDictionary *dictDevice = @{@"deviceId":@"",@"ip":@"",@"name":@"",@"macAddress":@"",@"upAndDownSize":@{@"up":@"",@"down":@""},@"networkName":@"",@"loginTime":@""};
//    WLWkSelf
//    NSDictionary *model = self.arrDevices[indexPath.row];
//    NSDictionary *paramsp = @{@"deviceId":model[@"deviceId"]};
//    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/untied" withParamsDic:paramsp success:^(NSDictionary *successDict) {
//        [weakSelf.arrDevices removeObjectAtIndex:indexPath.row];
//        [weakSelf.tbDevices deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
//    } error:^(NSError *error) {
//
//    } inView:self.view];
}
*/
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.arrDevices.count==0) {
        return 0.01;
    }
    return WLScaleX(20);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strRouters = @"routersCell";
    WLDeviceManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:strRouters];
    if (!cell) {
        cell = [[WLDeviceManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strRouters];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    WLRouterDeviceModel *dictRouter = self.arrDevices[indexPath.row];
    cell.routerDevices = dictRouter;
//    cell.labTitle.text = dictRouter.name;
//
//    cell.labDetail.text = [NSString stringWithFormat:@"MAC:%@",dictRouter.macAddress];;
//
////    if ([dictRouter[@"current"] integerValue]==1) {
//        cell.ivHead.image = [UIImage imageNamed:@"router_device"];
//        cell.labStatus.text = @"在线";
//        cell.labStatus.textColor = wlGreenColor;
////    }
////    else
////    {
////        cell.ivHead.image = [UIImage imageNamed:@"router_gray"];
////        cell.labStatus.text = @"离线";
////        cell.labStatus.textColor = wlLightTextColor;
////    }
//    if (dictRouter.access) {
//        cell.labBlack.alpha = 0;
//    }
//    else
//    {
//        cell.labBlack.alpha = 1.0;
//    }
//    cell.labTime.text = [WLCommonTool strToLoginTime:dictRouter.loginTime];
    
    return cell;
}

#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_data"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"还没有设备连接~";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
